from datetime import datetime
from typing import List, Optional
from pydantic import BaseModel
from bson import ObjectId

class PyObjectId(ObjectId):
    @classmethod
    def __get_validators__(cls):
        yield cls.validate

    @classmethod
    def validate(cls, v):
        if not ObjectId.is_valid(v):
            raise ValueError("Invalid objectid")
        return ObjectId(v)

    @classmethod
    def __modify_schema__(cls, field_schema):
        field_schema.update(type="string")

class ChatBase(BaseModel):
    participants: List[PyObjectId]
    type: str  # 'user_to_user', 'user_to_ai'

class ChatCreate(ChatBase):
    pass

class ChatUpdate(BaseModel):
    participants: Optional[List[PyObjectId]] = None
    type: Optional[str] = None

class ChatInDBBase(ChatBase):
    id: PyObjectId
    created_at: datetime
    updated_at: datetime
    last_message_id: Optional[PyObjectId] = None

    class Config:
        arbitrary_types_allowed = True
        json_encoders = {ObjectId: str}

class Chat(ChatInDBBase):
    pass

class ChatInDB(ChatInDBBase):
    pass